package com.itheima.test21;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

/**
 * 键盘录入3个学生信息(姓名,语文成绩,数学成绩,英语成绩)。
 * <p>
 * 要求按照成绩总分从高到低写入文本文件，最后在从文件中把读取数据显示在控制台
 * <p>
 * 格式：姓名,语文成绩,数学成绩,英语成绩 举例：林青霞,98,99,100
 */
public class Test21 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException {
        Class clazz = Class.forName("com.itheima.test21.Student");
        ArrayList<Student> as = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入第" + (i + 1) + "个学生的姓名");
            String name = sc.nextLine();
            System.out.println("语文成绩:");
            Integer chineseScore = sc.nextInt();
            System.out.println("数学成绩:");
            Integer mathScore = sc.nextInt();
            System.out.println("英语成绩:");
            Integer englishScore = sc.nextInt();
            Constructor constructor = clazz.getDeclaredConstructor(String.class,
                    Integer.class, Integer.class, Integer.class);
            Student student = (Student) constructor.newInstance(name, chineseScore, mathScore, englishScore);
            as.add(student);
        }
        Collections.sort(as, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int result = o2.getTotalScore() - o1.getTotalScore();
                return result;
            }
        });
        BufferedWriter bw = new BufferedWriter(new FileWriter(new File("TEST10.16\\student.txt")));
        bw.write("姓名,语文成绩,数学成绩,英语成绩\r\n");
        int count = 0;
        while (count < as.size()) {
            if (count == as.size() - 1) {
                bw.write(as.get(count).getName() + "," + as.get(count).getChineseScore() +
                        "," + as.get(count).getMathScore() + "," + as.get(count).getEnglishScore());
            } else {
                bw.write(as.get(count).getName() + "," + as.get(count).getChineseScore() +
                        "," + as.get(count).getMathScore() + "," + as.get(count).getEnglishScore() + "\r\n");
            }
            count++;
            bw.flush();
        }
        bw.close();
        System.out.println("数据写入完毕");
        System.out.println("文件中的数据展示如下:");
        BufferedReader br = new BufferedReader(new FileReader(new File("TEST10.16\\student.txt")));
        char[] chars = new char[1];
        int len;
        while ((len = br.read(chars)) != -1) {
            String str = new String(chars);
            System.out.print(str);
            System.out.println(br.readLine());
        }
    }
}
